<?php

namespace app\store\model\campus;

use app\common\model\campus\CoursesCategory as CoursesCategoryModel;
use Lvht\GeoHash;

/**
 * 校区模型
 * Class Campus
 * @package app\store\model\store
 */
class CoursesCategory extends CoursesCategoryModel
{
    /**
     * 获取列表数据
     * @param int $campus_id
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList( $campus_id = 0)
    {
        $campus_id > 0 && $this->where('campus_id', '=', (int)$campus_id);
        // 查询列表数据
        return $this->with(['campus','category','category.image'])
            ->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 获取所有校区列表
     * @param array $param
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getAllList($param = [])
    {
        return (new static)->setListQueryWhere($param)->select();
    }

    /**
     * 设置列表查询条件
     * @param array $param
     * @return $this
     */
    private function setListQueryWhere($param = [])
    {
        // 查询参数
        $param = array_merge(['search' => '', 'status' => null,], $param);
        !empty($param['search']) && $this->where('campus_name|phone', 'like', "%{$param['search']}%");
        is_numeric($param['status']) && $this->where('status', '=', (int)$param['status']);
        return $this->where('is_delete', '=', '0')->order(['sort' => 'asc', 'create_time' => 'desc']);
    }


    /**
     * 添加校区
     * @param array $data
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function add(array $data)
    {
        $isHas = $this->where('campus_id',$data['campus_id'])->where('courses_category_id',$data['courses_category_id'])->select();

        if ($data['campus_id'] && $data['courses_category_id'] && count($isHas) == 0){
            $data['wxapp_id'] = self::$wxapp_id;
            return $this->allowField(true)->save($data);
        }else{
            return false;
        }

    }

    /**
     * 编辑记录
     * @param $data
     * @return false|int
     */
    public function edit($data)
    {
        $isHas = $this->where('campus_id',$data['campus_id'])
            ->where('courses_category_id',$data['courses_category_id'])
            ->where('id','<>',$this->id)
            ->select();

        if (!$this->validateForm($data) || count($isHas) > 0) {
            return false;
        }
        return $this->allowField(true)->save($data) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->delete();
    }


    /**
     * 表单验证
     * @param $data
     * @return bool
     */
    private function validateForm($data)
    {
        if (!isset($data['campus_id']) || empty($data['courses_category_id'])) {
            $this->error = '请选择校区或专业';
            return false;
        }
        return true;
    }

}